#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-6 上午9:32
# @Author  : Tom
# @Site    : 
# @File    : utils.py
# @Software: PyCharm

from meiduo_mall.utils import meiduo_json
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response):
    '''
    用户登录后将未登录时购物车的商品添加到登录后的购物车中区
    :param request: 获得的请求
    :param user: 用户
    :param response: 响应
    :return:
    '''

    # 构造新的 字典: 键:cart_user.id        值是: {键:sku_id:值:count}
    # 构造新的选择的 集合, selected_user.id  值是: sku_id
    # cookie中存储的数据:
    #  carts_dict[sku_id] = {
    #            'count': sku_count,
    #           'selected': True,
    #           'sku_id': sku_id
    #       }
    # 思路
    # 1.应该将cookies中值读取出来
    # 2.拼接成两个表： 1.字典和集合
    # 3.向字典中加入拼接的表
    # 4.如果选中，则选中集合中添加该表，如果没有选中，则从选中集合中删除该表
    # 读取cookie值
    carts_str = request.COOKIES.get('carts')
    if not carts_str:
        return response
    # 解密
    carts_dict = meiduo_json.loads(carts_str)
    print(carts_dict)
    # 先定义两个列表和一个有序集合
    new_cart_dict = {}
    new_cart_selected_add = []
    new_cart_selected_remove = []
    # 拼接字典和选中集合
    for index, value in carts_dict.items():
        new_cart_dict[index] = value['count']
        if value['selected']:
            new_cart_selected_add.append(value['sku_id'])
        else:
            new_cart_selected_remove.append(value['sku_id'])
    # 向redis中存储该数据
    redis_cli = get_redis_connection('carts')
    redis_pipe = redis_cli.pipeline()
    redis_pipe.hmset('cart%d' % request.user.id, new_cart_dict)
    print(new_cart_selected_add)
    print(new_cart_selected_remove)
    # 如果选中，则选中集合中添加该表，如果没有选中，则从选中集合中删除该表
    if new_cart_selected_add:
        redis_pipe.sadd('selected%d' % request.user.id, *new_cart_selected_add)
    if new_cart_selected_remove:
        redis_pipe.srem('selected%d' % request.user.id, *new_cart_selected_remove)
    redis_pipe.execute()
    response.delete_cookie('carts')
    return response







